package com.example.mq.filter;

import com.example.mq.config.contant.StaticConstant;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 邹宇杰
 * @email 2901570623@qq.com
 * @date 2022/3/18 14:34
 */
public class AuthorizationFilter extends BasicAuthenticationFilter {

    private UserDetailsService userDetailsService;

    public AuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    public AuthorizationFilter(AuthenticationManager authenticationManager, UserDetailsService userDetailsService) {
        super(authenticationManager);
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String authorizationHeader = request.getHeader(StaticConstant.Authorization.getName());
        if(authorizationHeader == null || !authorizationHeader.startsWith(StaticConstant.AUTHPREFIX)){
            chain.doFilter(request, response);
            return;
        }
        String token = authorizationHeader.replace(StaticConstant.AUTHPREFIX, "");
        String username = Jwts.parser()
                .setSigningKey("demo1")
                .parseClaimsJws(token)
                .getBody()
                .getSubject();

        if(username != null){
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, userDetails.getAuthorities());

            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }
        chain.doFilter(request, response);
    }
}
